import Vue from 'vue'
import VueRouter from 'vue-router'
import login from '@/views/user/login.vue'
import layout from '@/views/layout.vue'
import movie from '@/views/movie/movie.vue'
import qa from '@/views/qa/qa.vue'
import home from '@/views/home/home.vue'
import user from '@/views/user/user.vue'
import notfound from '@/views/notfound/notfound.vue'
import edit from '@/views/user/edit.vue'


Vue.use(VueRouter)

const routes = [
  {
    name:"edit",
    path:"/edit",
    component:edit 
  },
 {
   name:"login",
   path:"/login",
   component:login
 },
 {
  name:"layout",
  path:"/",
  component:layout,
  children:[
    {
      name:"movie",
      path:"/movie",
      component:movie
    },
    {
      name:"qa",
      path:"/qa",
      component:qa
    },
    {
      name:"user",
      path:"/user",
      component:user,
      meta:{
        isLogin:true
      }
    },
    {
      name:"home",
      path:"/home",
      component:home
    },
    {
      path:"/",
      redirect:"/home"
    }
  ]
 },
 {
  name:"notfound",
 path:"/notfound",
 component:notfound
},
{
  path:"*",
 redirect:"/notfound"
},
]
const originalPush = VueRouter.prototype.push
//(2)替换原型链中的push
VueRouter.prototype.push = function push (location, onResolve, onReject) {
  if (onResolve || onReject) {
    // 正常执行
    //originalPush.call() : 我们自定义的push底层还是调用默认的push
    return originalPush.call(this, location, onResolve, onReject)
  }
  //如果有异常，本来这个err默认是抛出的，我们直接不做任何处理（给吞掉了）
  /* 
  底层默认是抛出异常：err => {throw err}
  我们不抛出，不做任何处理：err => err
  */
  return originalPush.call(this, location).catch(err => err)
}

const router = new VueRouter({
  routes
})

//导入token工具包
import { getToken } from '@/utils/token.js'
import { Toast } from 'vant'

// 注册导航守卫 (全局前置守卫  跳转之前执行)
router.beforeEach((to, from, next) => {
  
  //判断用户没有没有登录
  if( to.meta.isLogin && !getToken() ){
    //没有登录，则跳转登录页
    next({path:'/login'})
  }else{
    //有登录，正常跳转
    next()
  }
})
export default router
